<template>
    <el-form ref="formRef" :model="form.trigger" :rules="rules" label-width="100px">
        <el-row>
            <el-col :lg="24">
                <el-form-item label="触发模式" prop="type">
                    <el-radio-group v-model="form.trigger.type">
                        <el-radio-button v-for="item in trigger_type" :key="item.value" :value="item.value">
                            {{ item.label }}
                        </el-radio-button>
                    </el-radio-group>
                </el-form-item>
            </el-col>

            <el-col :lg="12">
                <el-form-item label="启动模式" prop="startMode">
                    <el-radio-group v-model="form.trigger.startMode" @change="onStartupChange">
                        <el-radio-button v-for="item in startup_type" :key="item.value" :value="item.value">
                            {{ item.label }}
                        </el-radio-button>
                    </el-radio-group>
                </el-form-item>
            </el-col>
            <el-col :lg="12">
                <el-form-item label="预约时间" prop="effictStartTime" v-if="form.trigger.startMode == 2">
                    <el-date-picker v-model="form.trigger.effictStartTime" type="datetime" placeholder="请选择预约时间"
                        value-format="YYYY-MM-DDTHH:mm:ss" />
                </el-form-item>
            </el-col>
            <el-col :lg="12">
                <el-form-item label="有效期至" prop="forever">
                    <el-radio-group v-model="form.trigger.forever" @change="onForeverChange">
                        <el-radio-button key="0" :value="false">指定时间</el-radio-button>
                        <el-radio-button key="1" :value="true"> 永久 </el-radio-button>
                    </el-radio-group>
                </el-form-item>
            </el-col>
            <el-col :lg="12">
                <el-form-item label="指定时间" prop="effictEndTime" v-if="!form.trigger.forever">
                    <el-date-picker v-model="form.trigger.effictEndTime" type="datetime" placeholder="请选择截止时间"
                        format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DDTHH:mm:ss" />
                </el-form-item>
            </el-col>
            <el-col :lg="12">
                <el-form-item label="执行间隔(s)" prop="interval" v-if="form.trigger.type == 'simple'">
                    <el-input-number v-model="form.trigger.interval" :min="1" :max="999" controls-position="right" />
                </el-form-item>
            </el-col>
            <el-col :lg="12">
                <el-form-item label="执行次数" prop="repeat" v-if="form.trigger.type == 'simple'">
                    <el-input-number v-model="form.trigger.repeat" :min="1" :max="999" controls-position="right" />
                </el-form-item>
            </el-col>
            <el-col :lg="24">
                <el-form-item label="表达式(Cron)" prop="cron" v-if="form.trigger.type == 'cron'">
                    <el-input v-model="form.trigger.cron" placeholder="请输入cron表达式" clearable>
                        <template #append>
                            <el-button type="primary" link icon="clock" style="display: inline-flex;"
                                @click="crontabShow = true">在线生成</el-button>
                        </template>
                    </el-input>
                </el-form-item>
            </el-col>
            <el-col :lg="24">
                <el-form-item label="触发备注" prop="description">
                    <el-input v-model="form.trigger.description" type="textarea" :rows="6" resize="none"
                        placeholder="请输入备注"></el-input>
                </el-form-item>
            </el-col>
        </el-row>
    </el-form>

    <el-dialog v-model="crontabShow" append-to-body destroy-on-close draggable align-center width="680px">
        <Crontab @hide="crontabShow = false" @fill="crontabFill" :expression="cronExpression" />
    </el-dialog>

</template>

<script setup>
import { trigger_type, startup_type } from '../status.js';
import { isValidCron } from "cron-validator";
import Crontab from "@/components/Crontab"
import dayjs from 'dayjs'
defineOptions({ title: '执行条件' })
const form = defineModel({
    type: Object,
    default: {
        trigger: {
            type: 'simple',
            interval: 10,
            repeat: 5,
            startMode: 0,
            forever: true,
            effictEndTime: undefined,
            immediate: false,
            effictStartTime: undefined,
        },
    }
})
const formRef = ref();
const crontabShow = ref(false);
const cronExpression = ref();

const validateCron = (rule, value, callback) => {
    if (!value) {
        return callback(new Error('Cron表达式不能为空'));
    }

    try {
        const isValid = isValidCron(value, {
            alias: true,        // 允许别名（如 @yearly）
            allowBlankDay: true, // 允许日期中的空白
            seconds: true       // 必须包含秒（Quartz格式特性）
        });

        if (!isValid) {
            throw new Error('无效的Cron表达式');
        }

        // Quartz特有的年字段校验（可选）
        const parts = value.trim().split(/\s+/);
        if (parts.length !== 7 && parts.length !== 6) {
            throw new Error('Quartz cron需要6或7个字段（包含秒和年）');
        }

        callback();
    } catch (error) {
        callback(new Error(error.message || '无效的Cron表达式'));
    }
};

const rules = ref({
    effictStartTime: [{ required: true, message: "请选择预约时间", trigger: "blur", type: 'date' }],
    effictEndTime: [{ required: true, message: "请选择指定时间", trigger: "blur", type: 'date' }],
    interval: [{ required: true, message: "请输入间隔时间", trigger: "blur", type: 'number' }],
    repeat: [{ required: true, message: "请输入执行时间", trigger: "blur", type: 'number' }],
    cron: [
        { required: true, validator: validateCron, trigger: 'blur' }
    ]
});




//校验
const validate = () => {
    const validateForm = formRef.value?.validate;
    console.log(form.value)
    if (!validateForm) {
        return Promise.reject(new Error('validate 方法不存在'));
    }
    return validateForm();
}

//启动模式改变时
const onStartupChange = (value) => {
    if (value == 2) {
        //默认预约在一个小时后
        form.value.trigger.effictStartTime = dayjs().add(1, 'hour').format('YYYY-MM-DDTHH:mm:ss')
    } else {
        form.value.trigger.effictStartTime = undefined;
    }
}

//有效期至改变时
const onForeverChange = (value) => {
    if (value == 0) {
        //默认为10天后
        form.value.trigger.effictEndTime = dayjs().add(10, 'day').format('YYYY-MM-DDTHH:mm:ss')
    } else {
        form.value.trigger.effictEndTime = undefined;
    }
}

//cron回传
const crontabFill = (value) => {
    form.value.trigger.cron = value;
}



onMounted(() => {
    //默认时间
    form.value.trigger.effictEndTime = dayjs().add(10, 'day').format('YYYY-MM-DDTHH:mm:ss')
});

defineExpose({ validate });

</script>

<style lang="scss" scoped></style>